package com.bhkj.websocketlibrary.ws;

import android.os.Handler;
import android.os.Message;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.ThreadUtils;

import org.java_websocket.enums.ReadyState;

import java.net.URI;
import java.util.concurrent.TimeUnit;


public class WsTask extends ThreadUtils.Task {

    private WsCoreClient wsCoreClient;
    private Handler mHandler;
    private boolean isInit;
    //重连的次数 最多二十次
    private int reconnectCount = 1;

    public WsTask(Handler handler) {
        this.mHandler = handler;

    }

    @Override
    public Object doInBackground() throws Throwable {
        initClient();
        return null;
    }

    @Override
    public void onSuccess(Object result) {

    }

    @Override
    public void onCancel() {

    }

    @Override
    public void onFail(Throwable t) {

    }

    private void initClient() {
        if (wsCoreClient == null) {
            wsCoreClient = new WsCoreClient(URI.create(WsConfig.getInstance().getUrl()), mHandler) {
                @Override
                public void onClose(int code, String reason, boolean remote) {
                    super.onClose(code, reason, remote);
                    LogUtils.d("client:" + code + "-" + reason + "-" + remote);

                    //只要断开就开启断线重连,并且在网络连接的状态下
                    if (NetworkUtils.isConnected()){
                        reconnectLogic();
                    }

                }
            };
        }
        //ping检测是否断线，如果是断线就开始重连 心跳检测
        wsCoreClient.setConnectionLostTimeout(20);

    }

    public WsCoreClient getWsCoreClient() {
        return wsCoreClient;
    }

    public void connect() {
        close();
        if (wsCoreClient == null) {
            return;
        }
        if (wsCoreClient.isOpen()) {
            return;
        }
        ReadyState readyState = wsCoreClient.getReadyState();
        if (ObjectUtils.equals(readyState, ReadyState.NOT_YET_CONNECTED) && !isInit) {
            isInit = true;
            connectLogic();
        } else if (isInit || ObjectUtils.equals(readyState, ReadyState.CLOSING) || ObjectUtils.equals(readyState, ReadyState.CLOSED)) {
            reconnectLogic();
        }
    }

    private void connectLogic() {
        try {
            boolean b = wsCoreClient.connectBlocking(10, TimeUnit.SECONDS);
            if (b) {
                updateStatus(WsContact.CONNECT_SUCCESS, "连接成功");
            } else {
                updateStatus(WsContact.CONNECT_ERROR, "连接失败");
                reconnectLogic();
            }
            LogUtils.d("连接:" + b);
        } catch (InterruptedException e) {
            e.printStackTrace();
            updateStatus(WsContact.CONNECT_ERROR, e.getMessage());
        }
    }

    private void reconnectLogic() {
        ThreadUtils.executeBySingleAtFixRate(reconnectTask(), 0, 5, TimeUnit.SECONDS);
    }

    private ThreadUtils.SimpleTask<Void> reconnectTask() {
        close();
        return new ThreadUtils.SimpleTask<Void>() {
            @Override
            public Void doInBackground() throws Throwable {
                if (wsCoreClient == null) {
                    return null;
                }

                try {
                    LogUtils.d("执行重新连接" + wsCoreClient.getReadyState() + "-" + wsCoreClient.isClosed());
                    if ((wsCoreClient.isClosing()||wsCoreClient.isClosed()) && !wsCoreClient.reconnectBlocking()) {
                        reconnectCount++;
                        LogUtils.d("重连第" + reconnectCount + "次");
                    }else if (wsCoreClient.isOpen()) {
                        LogUtils.d("重连成功" + reconnectCount + "次");
                        ThreadUtils.cancel(this);
                        reconnectCount = 1;
                    }

//                    if (reconnectCount >= 100) {
//                        reconnectCount = 1;
//                        ThreadUtils.cancel(this);
//                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }
                return null;
            }

            @Override
            public void onSuccess(Void result) {

            }
        };
    }

    public void sendMsg(String msg) {
        if (wsCoreClient != null && wsCoreClient.isOpen()) {
            LogUtils.d("发送消息:"+msg);
            wsCoreClient.send(msg);
        }
    }


    public void close() {
        try {
            if (wsCoreClient != null && wsCoreClient.isOpen()) {
                wsCoreClient.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updateStatus(int type, String msg) {
        Message message = new Message();
        message.what = type;
        message.obj = msg;
        if (mHandler != null) {
            mHandler.handleMessage(message);
        }
    }
}
